//
//  XTVCOfplayview.m
//  TTLestening
//
//  Created by dllo on 16/3/29.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "XTVCOfplayview.h"
#import "DWBubbleMenuButton.h"
#import "XTCellOfgeciLrc.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "XCModelForEveryone.h"
#import <AVOSCloud.h>
#import "ZFDownloadViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "Masonry.h"
#import "ZFPlayerControlView.h"
#import "ZFBrightnessView.h"
#import "ZFPlayer.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width

#define HEIGHT [UIScreen mainScreen].bounds.size.height




@interface XTVCOfplayview ()<UICollectionViewDataSource,UICollectionViewDelegate>


@property (nonatomic,retain)UIImageView *imageback;

@property (nonatomic,retain)UICollectionView *colllecion;

@property (nonatomic,retain)UICollectionViewFlowLayout *flowLatout;

@property (nonatomic,assign)BOOL isRotation;

@property (weak, nonatomic) IBOutlet UIImageView *yuanimage;

@property (nonatomic, assign)CGFloat totalMovieDuration;
@property (nonatomic, strong)NSArray *array;
@property (nonatomic, assign)NSInteger index;

@property (nonatomic, strong)NSMutableArray *downloadObjectArr;
@end

@implementation XTVCOfplayview


-(void)dealloc{
    
    
    [self.colllecion removeObserver:self forKeyPath:@"contentOffset"];
    
}


- (void)viewDidLoad {
    
    
    
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"currenTime" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        float currentTime = [[note.userInfo objectForKey:@"current"] floatValue];
        float rem = [[note.userInfo objectForKey:@"total"] floatValue] - currentTime ;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60 ,(int)currentTime%60];
        
        self.jindutiao.value = currentTime / [[note.userInfo objectForKey:@"total"] floatValue];
        
        
        self.playedtime.text = currenT;
        self.willplaytime.text = totalT;
        
        [self.jindutiao addTarget:self action:@selector(toAnyTime:) forControlEvents:UIControlEventValueChanged];
        
    }];
    
   
    
    self.yuanimage.layer.cornerRadius = self.yuanimage.frame.size.width * 0.5;
    self.yuanimage.layer.masksToBounds = YES;
    self.yuanimage.layer.borderColor = [[UIColor whiteColor]CGColor];
    self.yuanimage.layer.borderWidth = 15;
   
    
    CABasicAnimation *animaation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animaation.fromValue = [NSNumber numberWithInt:0];
    animaation.toValue = [NSNumber numberWithInt:M_PI * 2];
    animaation.duration = 10;
    
    animaation.repeatCount = NSIntegerMax;
    
    animaation.autoreverses = NO;
    
    animaation.cumulative = YES;
    
    [self.yuanimage.layer addAnimation:animaation forKey:@"basicAnimation"];
    self.yuanimage.image = [UIImage imageNamed:@"201603160253169682.jpg"];
    
    self.isRotation = NO;
    
    
      self.imageback = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.imageback];
    
    self.imageback.image = [UIImage imageNamed:@"744bec7842.jpg"];
    
    [self.view sendSubviewToBack:self.imageback];
   
    self.flowLatout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLatout.minimumInteritemSpacing = 0;
    self.flowLatout.minimumLineSpacing = 0;
    self.flowLatout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLatout.itemSize = CGSizeMake(WIDTH, self.viewOfback.frame.size.height - 1);
    
    
    
    
    self.colllecion = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 1, WIDTH,self.viewOfback.frame.size.height - 1) collectionViewLayout:self.flowLatout];

    [self.viewOfback addSubview:self.colllecion];
    
     self.colllecion.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.colllecion.alpha = 0.02;
  
    self.colllecion.dataSource =self;
    self.colllecion.delegate = self;
    
    self.colllecion.backgroundColor = [UIColor blackColor];
    
    self.colllecion.pagingEnabled = YES;
    self.colllecion.bounces = NO;
    
    [self.colllecion registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"pool1"];
    
    [self.colllecion registerClass:[XTCellOfgeciLrc class] forCellWithReuseIdentifier:@"pool2"];
    
    self.colllecion.contentOffset = CGPointMake(WIDTH, 0);
    
    UILabel *homeLabel = [self createHomeButtonView];
    
    DWBubbleMenuButton *downMenuButton = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(WIDTH - 40,20,homeLabel.frame.size.width,homeLabel.frame.size.height)expansionDirection:DirectionDown];
    
    downMenuButton.homeButtonView = homeLabel;
    
    [downMenuButton addButtons:[self createDemoButtonArray]];
    
    [self.view addSubview:downMenuButton];

    [self addNotification];
    [self creatKVOAction];
}


- (void)addNotification {


    [[NSNotificationCenter defaultCenter] addObserverForName:@"postPlayView" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSInteger index = [[note.userInfo objectForKey:@"index"] integerValue];
        
        self.array = [note.userInfo objectForKey:@"array"];
        self.index = index;
        XCModelForEveryone *model = [[note.userInfo objectForKey:@"array"] objectAtIndex:index];
        self.songname.text = model.name;
        [self.yuanimage sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
        //NSLog(@"%@", model.name);
        
    }];



}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 3;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
   

    if (indexPath.row == 0) {
        
         UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor redColor];
        
        return cell;
    }else if (indexPath.row == 1){
        
        
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
        
        return cell;
    }else{
        
         XTCellOfgeciLrc *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool2" forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor brownColor];
        
        return cell;
    }
    
    
}


- (UILabel *)createHomeButtonView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    label.backgroundColor =[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
    [self.moresection addSubview:label];
    label.clipsToBounds = YES;
    
    return label;
}

- (NSArray *)createDemoButtonArray {
    NSMutableArray *buttonsMutable = [[NSMutableArray alloc] init];
    
    int i = 0;
    for (NSString *title in @[@"图片", @"专辑", @"推荐", @"睡眠"]) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [button setTitle:title forState:UIControlStateNormal];
        
        button.frame = CGRectMake(0.f, 0.f, 32.f, 32.f);
        button.backgroundColor = [UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.5f];
        
         button.layer.cornerRadius = button.frame.size.height / 2.f;
        button.clipsToBounds = YES;
        button.tag = i++;
        
        [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
        
        [buttonsMutable addObject:button];
    }
    
    return [buttonsMutable copy];
}

- (void)test:(UIButton *)sender {
  //  NSLog(@"Button tapped, tag: %ld", (long)sender.tag);

    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"currenTime" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                
       float currentTime = [[note.userInfo objectForKey:@"current"] floatValue];
        float rem = [[note.userInfo objectForKey:@"total"] floatValue] - currentTime ;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60 ,(int)currentTime%60];
        
        self.jindutiao.value = currentTime / [[note.userInfo objectForKey:@"total"] floatValue];
        
        
        self.playedtime.text = currenT;
        self.willplaytime.text = totalT;
        
        [self.jindutiao addTarget:self action:@selector(toAnyTime:) forControlEvents:UIControlEventValueChanged];
        
    }];
   
}


#warning 未完成,有问题
- (void)toAnyTime:(UISlider *) time {

    float currentTime = self.totalMovieDuration * time.value;
    //CMTime dragedCMTime = CMTimeMake(currentTime, 1);
//    [self.play seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
//        
//        // [self.play play];
//        
//    }];
    
   // float currentTime = [[note.userInfo objectForKey:@"current"] floatValue];
    float rem = self.totalMovieDuration - currentTime;

    NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60,(int)rem%60];
    NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60 ,(int)currentTime%60];

    
    self.playedtime.text = currenT;
    self.willplaytime.text = totalT;

}


- (IBAction)goback:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
        
        
    }];
    
}

- (IBAction)moresection:(id)sender {
    
    NSLog(@"更多选项");
}

- (IBAction)download:(id)sender {
    
    NSLog(@"下载");
    
    ZFDownloadViewController *down = [[ZFDownloadViewController alloc] init];
    
    
    //    if ([ZFHttpManager shared].networkStatus != ReachableViaWiFi) {
    //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前非wifi网络,确定要下载吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //        alert.tag = 110;
    //        [alert show];
    [self downloadTheVideo];
    
    //    }else {
    //    }
    
    [self presentViewController:down animated:YES completion:^{
        
        
        
        //   [[NSNotificationCenter defaultCenter] postNotificationName:@"starDownLoad" object:nil userInfo:@{@"array":self.array, @"index": [NSString stringWithFormat:@"%ld", self.index]}];
        
        
        
        
        //    [self downloadTheVideo];
        
    }];

    
}

- (void)initData{
    
    NSMutableArray *downloads = [ZFDownloadObject readDiskAllCache].mutableCopy;
    self.downloadObjectArr = @[].mutableCopy;
    NSMutableArray *downladed = @[].mutableCopy;
    NSMutableArray *downloading = @[].mutableCopy;
    for (ZFDownloadObject *obj in downloads) {
        if (obj.downloadState == ZFDownloadCompleted) {
            [downladed addObject:obj];
        }else {
            [downloading addObject:obj];
        }
    }
    [self.downloadObjectArr addObject:downladed];
    [self.downloadObjectArr addObject:downloading];
    //  [self.tableView reloadData];
    
    
}


- (void)downloadTheVideo {
    
    XCModelForEveryone *model = [self.array objectAtIndex:self.index];
    
    //  NSLog(@"%@", [model.urlList firstObject]);
    
    NSString *stuURL = [[model.urlList firstObject] objectForKey:@"url"];
    NSArray *array = [stuURL componentsSeparatedByString:@"?"];
    
    NSURL *videoURL = [NSURL URLWithString:[[model.urlList firstObject] objectForKey:@"url"]];
    
    // NSURL *videoURL = [NSURL URLWithString:@"http://baobab.wdjcdn.com/1456117847747a_x264.mp4"];
    
    NSString * fileName = ZFFileName(array.firstObject);
    __weak typeof(self) weakSelf = self;
    ZFDownloadOperation * downloadTask = nil;
    downloadTask = [[ZFHttpManager shared] download:videoURL.absoluteString
                                           savePath:[ZFDownloadObject videoDirectory]
                                       saveFileName:fileName
                                           response:^(ZFBaseOperation *operation, NSError *error, BOOL isOK) {
                                               if (isOK) {
                                                   ZFDownloadOperation * downloadOperation = (ZFDownloadOperation*)operation;
                                                   ZFDownloadObject * downloadObject = [ZFDownloadObject readDiskCache:operation.strUrl];
                                                   if (downloadObject == nil) {
                                                       NSLog(@"已经添加到下载队列");
                                                       downloadObject = [ZFDownloadObject new];
                                                   }
                                                   downloadObject.fileName = downloadOperation.saveFileName;
                                                   downloadObject.downloadPath = downloadOperation.strUrl;
                                                   downloadObject.downloadState = ZFDownloading;
                                                   downloadObject.currentDownloadLenght = downloadOperation.recvDataLenght;
                                                   downloadObject.totalLenght = downloadOperation.fileTotalLenght;
                                                   [downloadObject writeDiskCache];
                                                   [[NSNotificationCenter defaultCenter] postNotificationName:@"relo" object:nil];
                                                   
                                                   
                                               }else {
                                                   [weakSelf errorHandle:(ZFDownloadOperation *)operation error:error];
                                               }
                                           } process:^(ZFBaseOperation *operation, uint64_t recvLength, uint64_t totalLength, NSString *speed) {
                                               NSLog(@"recvLength = %llu totalLength = %llu speed = %@",recvLength , totalLength , speed);
                                           } didFinished:^(ZFBaseOperation *operation, NSData *data, NSError *error, BOOL isSuccess) {
                                               if (isSuccess) {
                                                   NSLog(@"下载成功");
                                                   [weakSelf saveDownloadStateOperation:(ZFDownloadOperation *)operation];
                                               }else {
                                                   [weakSelf errorHandle:(ZFDownloadOperation *)operation error:error];
                                                   if (error != nil &&
                                                       error.code == ZFCancelDownloadError) {
                                                       [weakSelf saveDownloadStateOperation:(ZFDownloadOperation *)operation];
                                                   }
                                               }
                                           }];
    
    if (downloadTask.requestStatus == ZFHttpRequestNone) {
        if (![[ZFHttpManager shared] waitingDownload]) {
            return;
        }
        
        ZFDownloadObject * downloadObject = [ZFDownloadObject readDiskCache:downloadTask.strUrl];
        if (downloadObject == nil) {
            NSLog(@"已经添加到下载队列") ;
            downloadObject = [ZFDownloadObject new];
        }
        downloadObject.fileName = fileName;
        downloadObject.downloadPath = videoURL.absoluteString;
        downloadObject.downloadState = ZFDownloadWaitting;
        downloadObject.currentDownloadLenght = 0;
        downloadObject.totalLenght = 0;
        [downloadObject writeDiskCache];
    }
}

- (void)saveDownloadStateOperation:(ZFDownloadOperation *)operation {
    ZFDownloadObject * downloadObject = [ZFDownloadObject readDiskCache:operation.strUrl];
    if (downloadObject != nil) {
        downloadObject.currentDownloadLenght = operation.recvDataLenght;
        downloadObject.totalLenght = operation.fileTotalLenght;
        [downloadObject writeDiskCache];
    }
}

- (void) errorHandle:(ZFDownloadOperation *)operation error:(NSError *)error {
    NSString * errInfo = error.userInfo[NSLocalizedDescriptionKey];
    if ([errInfo containsString:@"404"]) {
        NSLog(@"该文件不存在");
        ZFDownloadObject * downloadObject = [ZFDownloadObject readDiskCache:operation.strUrl];
        if (downloadObject != nil) {
            [downloadObject removeFromDisk];
        }
    }else {
        if ([errInfo containsString:@"已经在下载中"]) {
            //            [self.view toast:errInfo];
        }else {
            //            [self.view toast:@"下载失败"];
        }
    }
}






- (IBAction)talkabout:(id)sender {
    
    NSLog(@"评论");
}

- (IBAction)shoucng:(id)sender {
    
    NSLog(@"收藏");
    AVUser *avuser = [AVUser currentUser];
    NSLog(@"%@", avuser.username);
    if (avuser != nil) {
        
        AVObject *userObject = [[AVObject alloc] initWithClassName:[NSString stringWithFormat:@"c%@",avuser.username]];
        
        XCModelForEveryone *model = [self.array objectAtIndex:self.index];
        [userObject setObject:model.name forKey:@"songName"];
        [userObject setObject:model.picUrl forKey:@"pic"];
        [userObject saveInBackground];
        
        
    } else {
    
        NSLog(@"还没有登录");
    
    }
    
    
    
    
    
}
- (IBAction)sharewith:(id)sender {
    NSLog(@"分享");
}
- (IBAction)MV:(id)sender {
    
    NSLog(@"MV");
    
}
- (IBAction)playmodel:(id)sender {
    
    NSLog(@"播放模式");
}
- (IBAction)upsong:(id)sender {
    
    NSLog(@"上一首歌");
    
    --self.index;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lastSong" object:nil userInfo:@{@"array":self.array, @"index":[NSString stringWithFormat:@"%ld", self.index]}];
    
    XCModelForEveryone *model = [self.array objectAtIndex:self.index];
    self.songname.text = model.name;
    [self.yuanimage sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
    

    
    
    
    
}
- (IBAction)play:(id)sender {
    
    if (self.isRotation == NO) {
        CFTimeInterval stopTime = [self.yuanimage.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        
        self.yuanimage.layer.speed = 0;
        
        self.yuanimage.layer.timeOffset = stopTime;
        
    }else{
        CFTimeInterval stopTime = self.yuanimage.layer.timeOffset;
        
        self.yuanimage.layer.speed = 1.0;
        
        self.yuanimage.layer.timeOffset = 0;
        self.yuanimage.layer.beginTime = 0;
        
        self.yuanimage.layer.beginTime = [self.yuanimage.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
    }
    
    self.isRotation = !self.isRotation;
    
    
    NSLog(@"播放");
}
- (IBAction)downsong:(id)sender {
    NSLog(@"下一首歌");
    
    ++self.index;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"nextSong" object:nil userInfo:@{@"array":self.array, @"index":[NSString stringWithFormat:@"%ld", self.index]}];
    
    XCModelForEveryone *model = [self.array objectAtIndex:self.index];
    self.songname.text = model.name;
    [self.yuanimage sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];

    
    
    
}
- (IBAction)gedan:(id)sender {
    
    NSLog(@"歌单");
}
- (IBAction)jindutiao:(id)sender {
    
    NSLog(@"进度条");
    
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"currenTime" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//        
//        float currentTime = [[note.userInfo objectForKey:@"current"] floatValue];
//        float rem = [[note.userInfo objectForKey:@"total"] floatValue] - currentTime ;
//        
//        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60,(int)rem%60];
//        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60 ,(int)currentTime%60];
//        
//        self.jindutiao.value = currentTime / [[note.userInfo objectForKey:@"total"] floatValue];
//        
//        
//        self.playedtime.text = currenT;
//        self.willplaytime.text = totalT;
//        
//        [self.jindutiao addTarget:self action:@selector(toAnyTime:) forControlEvents:UIControlEventValueChanged];
//        
//    }];
    
}


-(void)creatKVOAction{
    [self.colllecion addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"ddd"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    CGFloat x = [[change objectForKey:@"new"]CGPointValue].x;
    
//    NSLog(@"%f",x);
    
    if (x > WIDTH) {
        self.colllecion.alpha = (x -WIDTH) / WIDTH;
    }else if (x < WIDTH){
        
        self.colllecion.alpha = (WIDTH - x) / WIDTH;
        
    }else{
        
        self.colllecion.alpha = 0.02;
        
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
